import axios from "axios";
import { getLyrics, getMusicUrl } from "../../utils/api/music";

export const LOAD_SONG = 'LOAD_SONG';
export const CTRL_SONG = 'CTRL_SONG';
export const OPEN_SONG_PAGE = 'OPEN_SONG_PAGE';
export const CLOSE_SONG_PAGE = 'CLOSE_SONG_PAGE';
export const SHOW_LYRICS = 'SHOW_LYRICS';
export const GET_URL_SYNC = 'GET_URL_SYNC';
export const GET_URL_ASYNC = 'GET_URL_ASYNC';
export const TOGGLE_LYRICS = 'TOGGLE_LYRICS';
export const loadSongAsync = item => dispatch => {
    let getSongUrl, getSongLyrics;
    getSongUrl = axios.get(getMusicUrl(item.id));
    getSongLyrics = axios.get(getLyrics(item.id));
    return Promise.allSettled([getSongUrl, getSongLyrics]).then(results => {
        console.log(results);
        let r = {
            url: '',
            lrc: null
        }
        if (results[0].status === "fulfilled") r.url = results[0].value.data.data[0].url;
        if (results[1].status === "fulfilled") r.lrc = results[1].value.data.lrc;
        dispatch(loadSong(item, r))
    });
}
export const loadSong = (item, meta) => {
    return {
        type: LOAD_SONG,
        item,
        meta
    }
}
export const ctrlSong = bool => {
    return {
        type: CTRL_SONG,
        bool
    }
}
export const openSongPage = () => {
    return {
        type: OPEN_SONG_PAGE
    }
}

export const closeSongPage = () => {
    return {
        type: CLOSE_SONG_PAGE
    }
}

export const showLyrics = lrc => {
    return {
        type: SHOW_LYRICS,
        lrc
    }
}
export const getMusicUrlSync = url => {
    return {
        type: GET_URL_SYNC,
        url
    }
}
export const getMusicUrlAsync = id => dispatch => {
    return axios.get(getMusicUrl(id)).then(res => dispatch(getMusicUrlSync(res.data.data[0].url))).catch(err => console.error(err));
}

export const toggleLyrics = bool => {
    return {
        type: TOGGLE_LYRICS,
        bool
    }
}